package a12_图论;

import java.util.Scanner;

/**
 * <p>
 * a08_孤岛的总面积复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/4/7
 */
public class a08_孤岛的总面积复习1 {

    //找到周边的陆地，将其临近的变成海洋，统计剩下的陆地的面积即可
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int rows = scanner.nextInt();
        int cols = scanner.nextInt();

        int[][] grid = new int[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                grid[i][j] = scanner.nextInt();
            }
        }

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(i == 0 || j == 0 || i == rows - 1 || j == cols - 1){
                    if(grid[i][j] == 1){
                        grid[i][j] = 0;
                        dfs(grid,i,j);
                    }

                }
            }
        }

        int result = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(grid[i][j] == 1){
                    result++;
                }
            }
        }
        System.out.println(result);

    }

    public static final int[][] dirs = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};
    private static void dfs(int[][] grid, int x, int y) {
        for (int[] dir : dirs) {
            int nextX = x + dir[0];
            int nextY = y + dir[1];

            if(nextX >= 0 && nextX < grid.length && nextY >= 0 && nextY < grid[0].length){
                if(grid[nextX][nextY] == 1){
                    grid[nextX][nextY] = 0;
                    dfs(grid, nextX, nextY);
                }
            }
        }
    }
}
